package com.miao.im.filter;

import cn.hutool.core.util.StrUtil;
import com.miao.im.common.BizCode;
import com.miao.im.common.Constant;
import com.miao.im.common.annotation.ApiAuth;
import com.miao.im.domain.UserDo;
import com.miao.im.repository.IUserRepository;
import com.miao.im.support.WebSessionHolder;
import com.miao.im.support.exception.AuthenticationException;
import com.miao.im.support.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Auther: miaoguoxin
 * @Date: 2021/4/12 21:09
 * @Description:
 */
@Component
@Slf4j
public class WebAuthInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserRepository userRepository;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        if (handler instanceof HandlerMethod) {

            HandlerMethod h = (HandlerMethod) handler;
            ApiAuth apiAuth = h.getMethodAnnotation(ApiAuth.class);
            if (apiAuth == null) {
                this.auth(request);
            } else {
                if (apiAuth.needAuth()) {
                    this.auth(request);
                }
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        WebSessionHolder.remove();
    }

    private void auth(HttpServletRequest request) throws AuthenticationException {
        String deviceNumber = request.getHeader(Constant.WEB_DEVICE_NUMBER_HEADER);
        if (StrUtil.isBlank(deviceNumber)) {
            throw new BizException(BizCode.PARAMS_ERROR, "缺少必要参数！");
        }
        String sessionId = request.getHeader(Constant.WEB_SESSION_HEADER);
        if (StrUtil.isBlank(sessionId)) {
            throw new AuthenticationException("请先登录");
        }
        UserDo userDo = userRepository.getBySessionId(sessionId).orElseThrow(() -> new AuthenticationException("登录已过期，请重新登录"));
        WebSessionHolder.set(userDo);
    }
}
